package com.rpj.stauy.config;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class RedisChatMemoryStore implements ChatMemoryStore {

    public static final String CHAT_MEMORY_PREFIX = "CHAT_MEMORY:";

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    //删除持久化记录
    @Override
    public void deleteMessages(Object o) {
        redisTemplate.delete(CHAT_MEMORY_PREFIX+o);
    }


    //获取持久化记录
    @Override
    public List<ChatMessage> getMessages(Object o) {
        String value = redisTemplate.opsForValue().get(CHAT_MEMORY_PREFIX + o);
        return ChatMessageDeserializer.messagesFromJson(value);
    }

    //添加持久化记录
    @Override
    public void updateMessages(Object o, List<ChatMessage> list) {
        redisTemplate.opsForValue()
                .set(CHAT_MEMORY_PREFIX+o, ChatMessageSerializer.messagesToJson(list));
    }
}
